iT邦幫忙

2021 iThome 鐵人賽

DAY 27
0
Modern Web

用Jest和Enzyme來寫React測試吧!!系列 第 27

【Day27】React Redux 原理及應用方法簡介 ╰(°ㅂ°)╯

  • 分享至 

  • xImage
  •  

What's Redux !? Redux 是一個用來集中管理state的一個library,

用了Redux我們可以直接取得或修改相同的state,不用再一層一層Component往下傳了!


原理

  • 透過一個根Component集中管理states(這個地方通常稱為store)
  • store裡的states是透過dispatch執行某個action(動作)來進行變化 (一般的states是透過setState來進行變化)
  • dispatch在選擇要執行哪一個action的時候,該action會被送到reducer裡去決定到底是dispatch哪個action,進而回傳新的store

重點

  • 如果有Component要使用store的話,就必須和store連結
  • dispatch action 是回傳新的store,而不是直接改變store內的states

在最上層Component鑲上Redux和其他Component連結store的方式

  1. 執行以下指令安裝redux

    npm install redux
    
  2. 在App.js的地方鑲上React Redux 的Provider ,且透過redux的createStore來建立store

    import { createStore } from "redux";
    import reducer from './reducers'
    const store = createStore(reducer)
    
    class App extends React.Component {
      render() {
        return (
          <Provider store={store}>
            <Component />
          </Provider>
        );
      }
    }
    
  3. 上面的程式碼我們會看到在建立store的時候需要傳入reducer (也就是放置action type 並回傳新store的地方),所以我們要建立reducer並傳入

    • 開啟一個新的js檔案
    • 設定要傳入reducer的初始states
    • 建立一個function 來決定要回傳哪個action裡的store (第一個參數為初始值的states,第二個參數為傳入的action)
    • 上面有提到說action是用return 的方式去回傳store,而不是直接改變state的值
    let initialState;
    
    initialState = {
       aa:""
    };
    
    const reducer = (state = initialState, action) => {
      switch (action.type) {
        case "action1":
           return {
                    ...state,
                    aa:"123"
                };
          break;
        case "action2":
          return {
                    ...state,
                    aa:"333"
                };
          break;
        default:
          return { ...state };
          break;
      }
    
    };
    
  4. 上述程式碼,我們在switch裡使用到action.type,通常我們會建立一個新的js檔案來放置action

    export const action1 = ()=>{
        return {type:'action1'}
    };
    export const action2 = ()=>{
        return {type:'action2'}
    };
    
  5. 在其他Component連結store的方式 (連結state和dispatch)

  • 連結state

    const mapStateToProps = (state) => {
      return { aa: state.aa };
    };
    
  • 連結dispatch

const mapDispatchToProps = (dispatch) => {
  return {
      action1:()=>{dispatch(action1())},
      action2:()=>{dispatch(action2())}
  };
};

以上是Redux的原理及使用方法的補充,

下一篇要來介紹跟Redux作用很像的React Query ,
小菜鳥個人是覺得React Query相對Redux好用滿多的 (⊙ꇴ⊙)


上一篇
【Day26】Function Component 生命週期 & Hook (´・∀・`)
下一篇
【Day28】React Query 簡易說明及使用 (´∀`)
系列文
用Jest和Enzyme來寫React測試吧!!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言